<template>
  <el-card class="profile-info-card">
    <h3 class="card-title">地址管理</h3>
    <el-table
        :data="addressList"
        style="width: 100%"
        border
        stripe
    >
      <el-table-column
          prop="receiver"
          label="收货人"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="address"
          label="地址"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="phone"
          label="电话"
          align="center"
      ></el-table-column>
      <el-table-column
          label="操作"
          align="center"
      >
        <template #default="scope">
          <el-button
              type="text"
              @click="deleteAddress(scope.row.addressId)"
              style="color: #f56c6c"
          >
            删除
          </el-button>
          <el-button
              type="text"
              @click="editAddress(scope.row)"
              style="color: #409eff"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
          small
          :hide-on-single-page="true"
          layout="prev, pager, next"
          @size-change="handleAddressSizeChange"
          @current-change="handleAddressCurrentChange"
          :current-page="addressPage.currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="addressPage.pageSize"
          :total="addressPage.total"
          class="pagination"
      ></el-pagination>
    </div>
    <el-form
        :model="newAddress"
        label-width="100px"
        class="address-form"
    >
      <el-form-item label="收货人">
        <el-input
            v-model="newAddress.receiver"
            placeholder="请输入收货人姓名"
        ></el-input>
      </el-form-item>
      <el-form-item label="地址">
        <el-input
            v-model="newAddress.address"
            placeholder="请输入地址"
        ></el-input>
      </el-form-item>
      <el-form-item label="电话">
        <el-input
            v-model="newAddress.phone"
            placeholder="请输入电话号码"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
            type="primary"
            @click="addAddress"
            :disabled="!newAddress.receiver || !newAddress.address || !newAddress.phone"
            v-if="editAddressIndex === -1"
        >
          添加
        </el-button>
        <el-button
            type="success"
            @click="saveAddress"
            v-if="editAddressIndex !== -1"
        >
          保存
        </el-button>
        <el-button
            type="warning"
            @click="clearForm"
        >
          清空
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import {mapGetters} from "vuex";
import {addAddress, deleteAddress, pageMyAddress, updateAddress} from "@/api/addressMannagementApi";

export default {
  name: 'AddressManagement',
  data() {
    return {
      addressList: [],
      newAddress: {
        addressId: '',
        receiver: '',
        address: '',
        phone: '',
        userId: ''
      },
      addressPage: {
        currentPage: 1,
        pageSize: 5,
        total: 0
      },
      editAddressIndex: -1
    };
  },
  computed: {
    ...mapGetters({
      getUser: 'user/getUser'
    })
  },
  methods: {
    fetchAddresses() {
      const params = {
        pageRequestDto: {
          page: this.addressPage.currentPage,
          size: this.addressPage.pageSize
        },
        user: this.getUser
      };
      pageMyAddress(params)
          .then(response => {
            this.addressList = response.data.records;
            this.addressPage.total = response.data.total;
          })
          .catch(error => {
            console.error('获取地址列表失败:', error);
          });
    },
    addAddress() {
      if (this.editAddressIndex !== -1) {
        this.$message.warning('请先保存或取消编辑操作');
        return;
      }
      this.newAddress.userId = this.getUser.userId;
      addAddress(this.newAddress)
          .then(response => {
            this.$message.success('地址添加成功！');
            this.newAddress = {
              addressId: '',
              receiver: '',
              address: '',
              phone: '',
              userId: ''
            };
            this.fetchAddresses();
          })
          .catch(error => {
            this.$message.error('地址添加失败，请稍后再试！');
            console.error('添加地址失败:', error);
          });
    },
    saveAddress() {
      if (this.editAddressIndex === -1) {
        this.$message.warning('没有正在编辑的地址');
        return;
      }
      updateAddress(this.newAddress)
          .then(response => {
            this.$message.success('地址修改成功！');
            this.newAddress = {
              addressId: '',
              receiver: '',
              address: '',
              phone: '',
              userId: this.getUser.userId
            };
            this.editAddressIndex = -1;
            this.fetchAddresses();
          })
          .catch(error => {
            this.$message.error('地址修改失败，请稍后再试！');
            console.error('修改地址失败:', error);
          });
    },
    deleteAddress(addressId) {
      deleteAddress(addressId)
          .then(response => {
            this.$message.success('地址删除成功！');
            this.fetchAddresses();
          })
          .catch(error => {
            this.$message.error('地址删除失败，请稍后再试！');
            console.error('删除地址失败:', error);
          });
    },
    editAddress(address) {
      this.newAddress = {
        addressId: address.addressId,
        receiver: address.receiver,
        address: address.address,
        phone: address.phone,
        userId: address.userId
      };
      this.editAddressIndex = address.addressId;
    },
    handleAddressSizeChange(newSize) {
      this.addressPage.pageSize = newSize;
      this.fetchAddresses();
    },
    handleAddressCurrentChange(newPage) {
      this.addressPage.currentPage = newPage;
      this.fetchAddresses();
    },
    clearForm() {
      // 清空表单内容并取消编辑模式
      this.newAddress = {
        addressId: '',
        receiver: '',
        address: '',
        phone: ''
      };
      this.editAddressIndex = -1;
      this.$message.info('已取消当前操作');
    }
  },
  mounted() {
    this.fetchAddresses();
  }
};
</script>

<style scoped>
.profile-info-card {
  margin-bottom: 20px;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-title {
  font-size: 24px;
  margin-bottom: 20px;
}

.el-table {
  margin-bottom: 20px;
}

.pagination {
  text-align: center;
  margin-bottom: 20px;
}

.address-form {
  margin-top: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end; /* 将分页条置于右侧 */
  width: 100%;
}

.el-form-item {
  margin-bottom: 15px;
}

.el-button {
  margin-right: 10px;
}
</style>